package gae.util.http.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

public class Cookie {
    
    private Map<String, String> params = new HashMap<String, String>();
    
    private List<String> headers = new ArrayList<String>(20);
    
    
    
    public void addCookieFromHeaderValue(String header) {
        StringTokenizer st = new StringTokenizer(header, ";");
        while (st.hasMoreTokens()) {
            String cookie = st.nextToken();
            if (cookie.contains("=")) {
                while (cookie.startsWith(" ")) {
                    cookie = cookie.substring(1);
                }
                StringTokenizer st2 = new StringTokenizer(cookie, "=");
                String key = null;
                String value = null;
                if (st2.hasMoreTokens()) {
                    key = st2.nextToken();
                }
                if (st2.hasMoreTokens()) {
                    value = st2.nextToken();
                }
                if (key != null && value != null) {
                    params.put(key, value);
                }
            }
        }
        
        headers.add(header);
    }
    
    public Set<String> paramKeySet() {
        return params.keySet();
    }
    
    public String getParam(String key) {
        return params.get(key);
    }
    
    public String getParamString(String key) {
        String value = params.get(key);
        if (value != null) {
            return key + "=" + params.get(key);
        }
        return null;
    }
    
    public void addParam(String key, String value, int index) throws ArrayIndexOutOfBoundsException{
        if (headers.size() == 0 && index == 0) {
            headers.add(key + "=" + value);
        } else if (headers.size() - 1 < index) {
            throw new ArrayIndexOutOfBoundsException();
        } else if (headers.size() == index) {
            headers.add(key + "=" + value);
        } else {
            String header = headers.get(index);
            headers.set(index, header + "; " + key + "=" + value);
        }
        params.put(key, value);
    }
    
    public List<String> getHeaders() {
        return this.headers;
    }
}
